//
//  AFHTTPSessionManager+Encrypt.m
//  
//
//  Created by 韩红坡 on 2017/2/22.
//
//

#import "AFHTTPSessionManager+Encrypt.h"
#import "HHPSecureConst.h"
#import "HHPSecureManager.h"

@implementation AFHTTPSessionManager (Encrypt)

- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
                                       URLString:(NSString *)URLString
                                      parameters:(id)parameters
                                  uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
                                downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
                                         success:(void (^)(NSURLSessionDataTask *, id))success
                                         failure:(void (^)(NSURLSessionDataTask *, NSError *))failure
{
    HHPSecureManager *manager = [HHPSecureManager shareManager];
    
    if (![manager checkUrlExcemtionWithString:URLString] && manager.secureEnable) {
        //加密
        HHPSecureLog(@"urlString = %@", URLString);
        
        if ([URLString containsString:@"?"]) {
            URLString = [NSString stringWithFormat:@"%@&encryptFlag=true", URLString];
        } else {
            URLString = [NSString stringWithFormat:@"%@?encryptFlag=true", URLString];
        }
        
        if ([method isEqualToString:@"POST"]) {
            AFHTTPSessionManager *manager = self;
            AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
            
            [manager.requestSerializer.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, NSString * _Nonnull obj, BOOL * _Nonnull stop) {
                [requestSerializer setValue:obj forHTTPHeaderField:key];
            }];
            
            manager.requestSerializer = requestSerializer;
        }
        
        HHPSecureLog(@"加密前：params = %@", parameters);
        parameters = [HHPSecure encryptAESDictionary:parameters];
        HHPSecureLog(@"加密后：params = %@", parameters);
    }
    
    
    NSError *serializationError = nil;
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
    if (serializationError) {
        if (failure) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu"
            dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
                failure(nil, serializationError);
            });
#pragma clang diagnostic pop
        }
        
        return nil;
    }
    
    __block NSURLSessionDataTask *dataTask = nil;
    dataTask = [self dataTaskWithRequest:request
                          uploadProgress:uploadProgress
                        downloadProgress:downloadProgress
                       completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
                           if (error) {
                               if (failure) {
                                   failure(dataTask, error);
                               }
                           } else {
                               
                               if (success) {
                                   NSMutableDictionary *responseResult = [NSMutableDictionary dictionaryWithDictionary:responseObject];
                                   
                                   if (![manager checkUrlExcemtionWithString:URLString] && manager.secureEnable) {
                                       id data = responseResult[@"data"];
                                       HHPSecureLog(@"解密前：responseResult = %@", responseResult);
                                       
                                       if (data && ![data isKindOfClass:[NSNull class]]) {
                                           NSString *decryptKey = data[@"decryptKey"];
                                           NSString *encryptData = data[@"encryptData"];
                                           if (decryptKey.length > 0 && encryptData.length > 0) {
                                               NSString *resultString = [HHPSecure decryptString:encryptData withFixedString:AESKeyFixedString withRandomString:decryptKey];
                                               
                                               data = [NSJSONSerialization JSONObjectWithData:[resultString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
                                               
                                               responseResult[@"data"] = data;
                                               
                                               HHPSecureLog(@"解密后：responseResult = %@", responseResult);
                                           } else {
                                               HHPSecureLog(@"不用解密");
                                           }
                                       } else {
                                           HHPSecureLog(@"不用解密");
                                       }
                                   }
                                   
                                   success(dataTask, responseResult);
                               }
                           }
                       }];
    
    return dataTask;
}

@end
